// 引用axios
import axios from 'axios'
import { getToken } from '@/utils/auth'
// 配置API接口地址
// 线上API接口地址
// var root = 'https://ys.hljnfb.com/data_service/'
// 测试API接口地址
var root = 'http://192.168.68.114:10088'
// 处理接口方法
function toType(obj) {
  return {}.toString
    .call(obj)
    .match(/\s([a-zA-Z]+)/)[1]
    .toLowerCase()
}
function filterNull(o) {
  for (var key in o) {
    if (o[key] === null) {
      delete o[key]
    }
    if (toType(o[key]) === 'string') {
      o[key] = o[key].trim()
    } else if (toType(o[key]) === 'object') {
      o[key] = filterNull(o[key])
    } else if (toType(o[key]) === 'array') {
      o[key] = filterNull(o[key])
    }
  }
  return o
}

function apiAxios(method, url, params, success, failure) {
  if (params) {
    params = filterNull(params)
  }
  var token = getToken()
  console.log(token)
  axios({
    method: method,
    headers: {
      Authorization: token, // localStorage.getItem('token')
    },
    url: url,
    data: method === 'POST' || method === 'PUT' ? params : null,
    params: method === 'GET' || method === 'DELETE' ? params : null,
    baseURL: root,
    withCredentials: false,
  })
    .then(function (res) {
      success(res.data)
    })
    .catch(function (ent) {
      // failure(ent)
    })
}
// 导出 请求方法
export default {
  get: function (url, params, success, failure) {
    return apiAxios('GET', url, params, success, failure)
  },
  post: function (url, params, success, failure) {
    return apiAxios('POST', url, params, success, failure)
  },
  put: function (url, params, success, failure) {
    return apiAxios('PUT', url, params, success, failure)
  },
  delete: function (url, params, success, failure) {
    return apiAxios('DELETE', url, params, success, failure)
  },
}
